package com.yuyu.config;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class SecurityConfiguration {
	private Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);

	@Bean
	public UserDetailsService myUserDetailsService() {
		// 基于内存的方式存储用户信息
		InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

		// 这里添加用户，模拟数据库用户表
		String[][] usersGroupsAndRoles = { { "system", "password", "ROLE_ACTIVITI_USER", "GROUP_user" },
				{ "reviewer", "password", "ROLE_ACTIVITI_USER", "GROUP_user" },
				{ "admin", "password", "ROLE_ACTIVITI_ADMIN", "GROUP_admin" } };
		for (String[] user : usersGroupsAndRoles) {
			List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
			logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings
					+ "]");
			inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]),
					authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList())));
		}
		return inMemoryUserDetailsManager;
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}